# jwt认证工具函数
from datetime import datetime, timedelta

import jwt
from flask import current_app


def create_token(payload, expiry=None, secret=None):
    """
    生成jwt
    :param payload: dict 载荷{user_id: xxx}
    :param expiry: datetime 有效期
    :param secret: 密钥
    :return: jwt
    """
    expiry = datetime.utcnow() + timedelta(days=current_app.config["EXPIRE_DAYS"])
    _payload = {"exp": expiry}
    _payload.update(payload)
    if secret is None:
        secret = current_app.config.get("SECRET_KEY")

    # 组成token
    token = jwt.encode(_payload, secret, algorithm="HS256")

    return token


def check_token(token, secret=None):
    """
    检验jwt
    :param token: jwt
    :param secret: 密钥
    :return: dict: payload
    """
    if secret is None:
        secret = current_app.config.get("SECRET_KEY")
    try:
        payload = jwt.decode(token, secret, algorithms=["HS256"])
    except jwt.PyJWTError:
        payload = None
    return payload
